#include "StdAfx.h"
#include "Parser.h"

const std::string init[] = { "*", "/", "+", "-" };
const std::set<std::string> Parser::operations(init, init + sizeof(init)/sizeof(std::string));

Parser::Parser(void)
{
}

Parser::~Parser(void)
{
}

float Parser::parse(std::string expr)
{
	Tree *tree = new Tree();
	parse_term(tree, expr);
	return 0;
}

void Parser::parse_term(Tree *tree, std::string term)
{
	int beginIndex = 0;
	int currentIndex = 0;
	int endIndex = 0;

	do { currentIndex++; }
	while (is_number(term.substr(beginIndex, currentIndex-beginIndex)));
		

	if (currentIndex - beginIndex > 0 && currentIndex == term.length())
		tree->value = atof(term.substr(beginIndex, currentIndex-beginIndex+1).c_str());
	else 
	{
		tree->left = new Tree();
		tree->left->value = atof(term.substr(beginIndex, currentIndex-beginIndex).c_str());

		beginIndex = currentIndex;
		//currentIndex++;
		//do { currentIndex++; }
		while (is_operator(term.substr(beginIndex, currentIndex-beginIndex)));
			//currentIndex++;

		tree->operation = term.substr(beginIndex, currentIndex-beginIndex);

		tree->right = new Tree();
		parse_term(tree->right, term.substr(currentIndex, term.length() - currentIndex));
	}
}

bool Parser::is_string(std::string str, std::string eq)
{
	return false;
}

bool Parser::is_number(std::string expr)
{
	for (std::string::iterator it = expr.begin() ; it < expr.end(); ++it)
		if (!isdigit(*it) || *it != '.') return false;
		else if (*it == '\0') return true;
	return true;
}

bool Parser::is_operator(std::string str)
{
	return operations.find(str) != operations.end();
}

//bool Parser::is_number(std::string expr, int start = 0, int lenght = 524288)
//{
//	for (int index = start; index < lenght; index++)
//		if (!isdigit(expr[index]) || expr[index] != '.') return false;
//		else if (expr[index] == '\0') return true;
//}


//bool Parser::has_number()
//{
//	bool result = false;
//	while (isspace(expression[counter])) counter++;
//	while (isdigit(expression[counter]) || expression[counter] == '.') 
//	{
//		counter++;
//		result = true;
//	}
//	while (isspace(expression[counter])) counter++;
//	return result;
//}
//
//bool Parser::has_operation()
//{
//	for (std::string::iterator it = expression.begin() ; it < expression.end(); ++it, ++counter)
//		if (*it == '^' || *it == '*' || *it == '/' || *it == '+' || *it == '-') return true;
//	return false;
//}

//bool Parser::has_operation(std::string expr, int start = 0, int lenght = 524288)
//{
//	for (int index = start; index < lenght; index++)
//		if (expr[index]
//}

//bool Parser::has_char(char c)
//{
//}
//
//float Parser::get_number()
//{
//	std::string result = "";
//
//	for (std::string::iterator it = expression.begin() ; it < expression.end(); ++it, ++counter)
//		if (isdigit(*it) || *it == '.') result += *it;
//		else break;
//			
//	return atof(result.c_str());
//}